<template>
  <div class="bwlgl">
    <a-search :change="paginationElement?.change" :list="list" v-model="form"></a-search>
    <a-card resize>
      <a-card>
        <el-button @click="handleInfo(null, true)">新增</el-button>
        <a-upload-data :confirm="handleUploadConfirm"></a-upload-data>
      </a-card>
      <a-table :data="data" :head="head">
        <template #qk="{ row }">
          <el-tag type="success">{{ '已完成' + row.completeNum }}</el-tag>
          <el-tag type="danger">{{ '未完成' + row.incompleteNum }}</el-tag>
        </template>
        <template #handle="{ row }">
          <el-link @click="handleInfo(row, true)">编辑</el-link>
          <el-link type="primary" @click="handleInfo(row, false)">查看</el-link>
          <a-link type="danger" :confirm="() => handleDelete(row)">删除</a-link>
        </template>
      </a-table>
      <a-pagination ref="paginationElement" :total="total" :change="getTableData"></a-pagination>
      <a-dialog :title="title" v-model="show" :footer="edit" :confirm="handleConfirm">
        <a-form ref="formElement" :list="rowList" v-model="rowForm" :inline="true" :disabled="!edit"> </a-form>
      </a-dialog>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { deleteData, save, tableData, uploadData } from '../../api/bwlgl/bwlgl'
import { upload } from '../../api/common'
import { ElMessage } from 'element-plus'
import deptTree from '../../store/deptTree'

interface BWLGL {
  id: string
  memorandumId: string
  leadDept: number[]
  leadDeptLabel: string
  coordinateDept: number[]
  coordinateDeptLabel: string
  memorandumReferenceFileName: string
  [key: string]: unknown
}

const paginationElement = ref<APaginationInstance | null>()
const formElement = ref<AFormInstance | null>(null)

const bwlType = [
  { label: '激励', value: '1' },
  { label: '惩戒', value: '0' }
]

const form = ref({})
const list = ref<FormItem[]>([
  { prop: 'objectName', 'aria-label': '备忘录名称', type: 'input' },
  {
    prop: 'objectCodeValue',
    'aria-label': '备忘录类型',
    type: 'select',
    data: bwlType
  },
  {
    prop: 'memorandumState',
    'aria-label': '备忘录状态',
    type: 'select',
    data: [
      { label: '已完成', value: '1' },
      { label: '填报中', value: '0' }
    ]
  }
])

const data = ref<BWLGL[]>([])
const head = ref([
  { prop: 'memorandumName', label: '备忘录名称' },
  { prop: 'leadDeptLabel', label: '牵头部门' },
  { prop: 'coordinateDeptLabel', label: '配合部门' },
  { prop: 'qk', label: '完成情况' },
  { prop: 'bwlLabel', label: '备忘录类型' },
  { prop: 'handle', label: '操作', fixed: 'right' }
])
const total = ref(0)

function getTableData(currentPage: number, size: number) {
  tableData<BWLGL>({
    size,
    currentPage,
    ...form.value
  }).then(({ data: result }) => {
    data.value = result.pageList.map((item) => {
      return {
        ...item,
        bwlLabel: bwlType.find((i) => i.value === item.memorandumType)?.label,
        leadDeptLabel: item.leadDept.map((i) => deptTree.getDeptTreeNameById(i)).join(','),
        coordinateDeptLabel: item.coordinateDept.map((i) => deptTree.getDeptTreeNameById(i)).join(',')
      }
    })
    total.value = result.totals
  })
}

const rowForm = ref<{
  memorandumReferenceFileName: UploadFilesCTM[]
  leadDeptList: DeptTree[]
  coordinateDeptList: DeptTree[]
  [key: string]: unknown
}>({
  memorandumReferenceFileName: [],
  leadDeptList: [],
  coordinateDeptList: []
})
const rowList = ref<FormItem[]>([
  { prop: 'memorandumName', 'aria-label': '备忘录名称', type: 'input', rules: [{ required: true, message: '请输入备忘录名称', trigger: 'blur' }] },
  { prop: 'memorandumType', 'aria-label': '备忘录类型', type: 'select', data: bwlType, rules: [{ required: true, message: '请选择备忘录类型', trigger: 'change' }] },
  {
    prop: 'leadDeptList',
    'aria-label': '牵头部门',
    type: 'deptTree2'
  },
  {
    prop: 'coordinateDeptList',
    'aria-label': '配合部门',
    type: 'deptTree2',
    rules: [{ required: true, message: '请选择配合部门', trigger: 'change' }]
  },
  {
    prop: 'memorandumRange',
    'aria-label': '所属范围',
    type: 'select',
    data: [
      { label: '国家', value: '1' },
      { label: '本地', value: '0' }
    ]
  },
  {
    prop: 'memorandumReferenceFileName',
    'aria-label': '附件',
    type: 'upload',
    formItemProps: {
      style: {
        width: '100%'
      }
    },
    'http-request': (data: FormData) => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          upload<UploadFileResponse>(data)
            .then(({ data: result }) => {
              resolve(result)
            })
            .catch(reject)
        }, 1000)
      })
    }
  }
])

const show = ref(false)
const title = ref('')
const edit = ref(false)

function handleInfo(row: BWLGL | null, e: boolean) {
  show.value = true
  rowForm.value = {
    ...row,
    memorandumReferenceFileName: row
      ? ([
          {
            name: row.memorandumReferenceFileName,
            status: 'success',
            uid: Date.now(),
            response: {
              name: row.memorandumReferenceFileName
            }
          }
        ] as UploadFilesCTM[])
      : [],
    leadDeptList: row
      ? row!.leadDept.map((i) => {
          return {
            id: i,
            label: deptTree.getDeptTreeNameById(i)
          }
        })
      : [],
    coordinateDeptList: row
      ? row!.coordinateDept.map((i) => {
          return {
            id: i,
            label: deptTree.getDeptTreeNameById(i)
          }
        })
      : []
  }
  edit.value = e
  title.value = e ? '编辑' : '查看'
}

function handleConfirm() {
  formElement.value?.element.validate((valid: boolean) => {
    if (valid) {
      save({
        ...rowForm.value,
        coordinateDept: rowForm.value.coordinateDeptList.map((i) => i.id),
        leadDept: rowForm.value.leadDeptList.map((i) => i.id),
        memorandumReferenceFileName: rowForm.value.memorandumReferenceFileName && rowForm.value.memorandumReferenceFileName[0] ? rowForm.value.memorandumReferenceFileName[0].response?.name : ''
      }).then(({ msg }) => {
        show.value = false
        paginationElement.value?.change()
        ElMessage.success(msg)
      })
    }
  })
}

function handleDelete(row: BWLGL) {
  deleteData(row.id).then(({ msg }) => {
    ElMessage.success(msg)
    paginationElement.value?.change()
  })
}

function handleUploadConfirm(formData: FormData, close: () => void) {
  uploadData(formData).then(({ msg }) => {
    ElMessage.success(msg)
    paginationElement.value?.change()
    close()
  })
}
</script>
